unit uSettings;

interface

type
  /// <summary>
  ///  This Singleton loads and saves the application settings automatically.
  /// </summary>
  TSettings = class
  private
    class var fInstance: TSettings;
  private
    fFilename : string;
    fHTTPPort: integer;
    fUseHTTPS: boolean;
    fWWWPath: string;
  public
    class constructor Create;
    class destructor Destroy;
    class property Instance: TSettings read fInstance;
  public
    constructor Create;
    procedure Load;
    procedure Save;
    // Settings
    property WWWPath: string read fWWWPath write fWWWPath;
    property HTTPPort: integer read fHTTPPort write fHTTPPort;
    property UseHTTPS: boolean read fUseHTTPS write fUseHTTPS;
  end;

implementation

uses
  IOUtils, uSerialHelper, uSpecialFolder, SysUtils;

{ TSettings }

class constructor TSettings.Create;
begin
  fInstance := TSettings.Create;
  fInstance.Load;
end;

constructor TSettings.Create;
begin
  fFilename := TSpecialFolder.CommonAppData + '\WebServer\config.json';
  TDirectory.CreateDirectory(ExtractFilePath(fFilename));
end;

class destructor TSettings.Destroy;
begin
  fInstance.Save;
  fInstance.Free;
end;

procedure TSettings.Load;
var
  s: string;
begin
  if TFile.Exists(fFilename) then
    s := TFile.ReadAllText(fFilename)
  else
    s := fInstance.serialize;
  fInstance.deserialize(s);
end;

procedure TSettings.Save;
var
  s: string;
begin
  s := fInstance.serialize;
  TFile.WriteAllText(fFilename, s);
end;

end.
